package com.atguigu.crowd.mvc.handler;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.atguigu.crowd.entity.Menu;
import com.atguigu.crowd.service.api.MenuService;
import com.atguigu.crowd.util.ResultEntity;

@Controller
public class MenuHandler {

	@Autowired
	private MenuService menuService;
	
	//删除菜单节点
	@ResponseBody
	@RequestMapping("/menu/remove.json")
	public ResultEntity<String> removeMenu(@RequestParam("id") Integer id){
		menuService.removeMenu(id);
		return ResultEntity.successWithoutData();
	}
	
	//更新菜单节点
	@ResponseBody
	@RequestMapping("/menu/update.json")
	public ResultEntity<String> updateMenu(Menu menu){
		menuService.updateMenu(menu);
		return ResultEntity.successWithoutData();
	}
	
	//添加菜单节点
	@ResponseBody
	@RequestMapping("/menu/save.json")
	public ResultEntity<String> saveMenu(Menu menu){
		menuService.saveMenu(menu);
		return ResultEntity.successWithoutData();
	}
	
	//获取菜单
	@ResponseBody
	@RequestMapping("/menu/get/menuTree.json")
	public ResultEntity<Menu> getMenuTree(){
		List<Menu> menuList = menuService.getAll();   
		Map<Integer, Menu> map = new HashMap<Integer, Menu>();
		Menu root = null;
		//把menu对象放入map中
		for (Menu menu : menuList) {
			Integer id = menu.getId();
			map.put(id,menu);
		}
		//判断是否有父节点
		for (Menu menu : menuList) {
			Integer pid = menu.getPid();
			if (pid==null) {//没有子节点
				root = menu;
				continue;
			}
			//将子节点放入根节点中
			Menu father = map.get(pid);
			father.getChildren().add(menu);
		}
		return ResultEntity.successWithData(root);
	}
}
